"use client"

import { Button, ButtonGroup } from "@nextui-org/react"
import { useMemo, useState } from "react";
import Production from "./Production";
import Product from "./Product";
import History from "./History";
import Teammate from "./Teammate";
import { selectReport } from "@/lib/features/report/reportSlice";
import { useAppSelector } from "@/lib/hooks";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { XingHaoType } from "@/type/report";
import toast from "react-hot-toast";
import { uploadFileExcel } from "@/api/team/tember/upload";
import { redirect } from "next/navigation";
import { selectUserDetail } from "@/lib/features/login/loginSlice";
import Supervise from "./Supervise";
import { selectTeamDetail } from "@/lib/features/team/teamSlice";


export type STATUS = 1 | 2 | 3 | 4

interface ColumnConfig {
    key: string;      // 数据字段名
    title: string;    // Excel显示列名
    width?: number;   // 可选列宽
}


const Report = ({ team_id }: { team_id: number }) => {

    const [status, setStatus] = useState<STATUS>(1)

    const data = useAppSelector(selectReport) ?? []

    const exportToExcel = async () => {
        // 假设已定义 columns 配置数组和 data 数据
        const columns: ColumnConfig[] = [
            { key: "tjbh", title: "台架编号", width: 10 },
            { key: "cpxm", title: "产品项目", width: 10 },
            { key: "jpsj", title: "节拍时间", width: 10 },
            { key: "kssj", title: "开始时间", width: 10 },
            { key: "jssj", title: "结束时间", width: 10 },
            { key: "lb", title: "连班", width: 10 },
            { key: "scgs", title: "生产工时", width: 10 },
            { key: "wssx", title: "5S收线", width: 10 },
            { key: "yxgs", title: "有效工时", width: 10 },
            { key: "trtj", title: "投入台架", width: 10 },
            { key: "llcn", title: "理论产能", width: 10 },
            { key: "scxl", title: "生产效率", width: 10 },
            { key: "jhsl", title: "计划数量", width: 10 },
            { key: "sjwc", title: "实际完成", width: 10 },
            { key: "xh", title: "型号", width: 10 },
            { key: "wcl", title: "完成率", width: 10 },
            { key: "bls", title: "不良数", width: 10 },
            { key: "trry", title: "投入人员", width: 10 },
            { key: "tjsj", title: "停机时间", width: 10 },
            { key: "czy", title: "操作员", width: 10 },
            { key: "bz", title: "备注", width: 10 },
            { key: "tjbh", title: "台架编号", width: 10 },
        ];

        // 1. 创建表头行
        const headerRow = columns.map(col => col.title);
        const worksheet = XLSX.utils.aoa_to_sheet([headerRow]);

        // 2. 转换数据内容
        const dataRows = data.map(item =>
            columns.map(col => {
                let value = ""
                if (col.key == 'xh' && item.xh != "") {
                    const dt: XingHaoType[] = JSON.parse(item.xh)
                    if (dt.length > 0) {
                        dt.forEach((o) => {
                            value += `${o.name}: ${o.price}\n`
                        })
                    }
                } else {
                    value = item[col.key] + ""
                }
                // 应用格式化函数（如果存在）
                return value;
            })
        );

        // 3. 添加数据到工作表
        XLSX.utils.sheet_add_aoa(worksheet, dataRows, { origin: -1 });

        // // 4. 设置列宽（可选）
        // worksheet['!cols'] = columns.map(col => ({
        //     wch: col.width || Math.max(
        //         col.title.length,
        //         ...data.map(item => {
        //             const val = col.key.split('.').reduce((o, k) => o?.[k], item);
        //             console.log(val);

        //             return String(val).length
        //         })
        //     ) + 2 // 增加2字符的缓冲
        // }));

        // 5. 创建 Workbook 并保存
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

        // 6. 生成 Excel 文件
        const excelBuffer = XLSX.write(workbook, {
            bookType: 'xlsx',
            type: 'array',
            bookSST: false // 禁用共享字符串表
        });

        // 7. 创建 Blob 并触发下载
        const blob = new Blob([excelBuffer], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const flag = await uploadExcel(blob, team_id)
        if (flag) {
            // 使用 file-saver 保存文件
            saveAs(blob, `数据导出_${new Date().toISOString().slice(0, 10)}.xlsx`);

            // （可选）添加埋点监控
            // console.log('Excel 导出完成', {
            //     columns: columns.map(c => c.key),
            //     rowCount: data.length
            // });
            toast.success("Excel 导出完成")
        } else {
            redirect("/login")
        }

    };

    const uploadExcel = async (blob: Blob, id: number): Promise<boolean> => {
        const reuslt = await uploadFileExcel(blob, id)
        if (reuslt) {
            return true
        } else {
            return false;
        }
    }

    const production = useMemo(() => {
        if (status === 1) {
            return (<Production menuChange={(v: STATUS) => setStatus(v)} team_id={team_id} />)
        } else {
            return (null)
        }

    }, [status, team_id])

    const product = useMemo(() => {

        if (status === 2) {
            return (<Product />)
        } else {
            return (null)
        }

    }, [status])

    const teammate = useMemo(() => {

        if (status === 3) {
            return (<Teammate team_id={team_id} />)
        } else {
            return (null)
        }

    }, [status, team_id])

    const history = useMemo(() => {

        if (status === 4) {
            return (<History team_id={team_id} />)
        } else {
            return (null)
        }

    }, [status])

    const { user_id } = useAppSelector(selectUserDetail)
    const team = useAppSelector(selectTeamDetail)

    return (
        <>
            {
                (team != undefined && team.user_id == user_id) ? (<>
                    <div className="w-full h-[100vh]  pt-4">
                        {
                            status === 1 ?
                                (<>
                                    {production}
                                </>) :
                                status === 2 ?
                                    (
                                        <>
                                            {product}
                                        </>
                                    ) :
                                    status === 3 ?
                                        (
                                            <>
                                                {teammate}
                                            </>
                                        ) :
                                        status === 4 ?
                                            (
                                                <>
                                                    {history}
                                                </>
                                            ) : null
                        }

                        <div className="w-full flex px-4 h-12 items-center justify-center absolute bottom-0 left-0">
                            <ButtonGroup variant="shadow">
                                <Button color={status === 1 ? "warning" : "default"} onPress={() => setStatus(1)} size="sm" className="w-1/2">生产</Button>
                                <Button color={status === 2 ? "warning" : "default"} onPress={() => setStatus(2)} size="sm" className="w-1/2">产品</Button>
                                <Button color={status === 3 ? "warning" : "default"} onPress={() => setStatus(3)} size="sm" className="w-1/2">队员</Button>
                                <Button color={status === 4 ? "warning" : "default"} onPress={() => setStatus(4)} size="sm" className="w-1/2">历史</Button>
                                <Button onPress={() => {
                                    exportToExcel()
                                }} color={!(status == 1) ? "default" : "warning"} isDisabled={!(status == 1)} size="sm" className="w-1/2">导出</Button>
                            </ButtonGroup>
                        </div>
                    </div>
                </>
                ) : (<>
                    <div className="w-full h-[100vh]  pt-4">
                        {
                            (status === 1) ?
                                (
                                    <>
                                        {
                                            <Supervise />
                                        }
                                    </>
                                ) : (
                                    <>
                                        {history}
                                    </>
                                )
                        }
                        <div className="w-full flex px-4 h-12 items-center justify-center absolute bottom-0 left-0">
                            <ButtonGroup variant="shadow">
                                <Button color={status === 1 ? "warning" : "default"} onPress={() => setStatus(1)} size="sm" className="w-1/2">生产</Button>
                                <Button color={status === 4 ? "warning" : "default"} onPress={() => setStatus(4)} size="sm" className="w-1/2">历史</Button>
                            </ButtonGroup>
                        </div>
                    </div>
                </>)
            }
        </>
    )
}

export default Report;